package router

import (
	"go-proxy/common"
	"go-proxy/config"
	"net/http"
)

var (
	routerHandlerMap = make(map[string]HandlerMatchRouter)
)

type HandlerMatchRouter interface {
	checkPath(route *config.Route, r *http.Request) bool
}

func InitHandlerMatchRouter() {
	routerHandlerMap[common.RoutePrefix] = NewPrefixRouter()
	routerHandlerMap[common.RouteExact] = NewExactRouter()
	routerHandlerMap[common.RouteRegex] = NewRegexRouter()
}

func Match(pathType string, route *config.Route, r *http.Request) bool {
	handler := routerHandlerMap[pathType]
	return checkDomain(route, r) && handler.checkPath(route, r) && checkHeader(route, r) && checkMethod(route, r)
}

func checkHeader(route *config.Route, r *http.Request) bool {
	headers := route.Headers
	if len(headers) <= 0 {
		return true
	}

	for key, value := range headers {
		if r.Header.Get(key) != value {
			return false
		}
	}
	return false
}

func checkMethod(route *config.Route, r *http.Request) bool {
	supportMethods := route.SupportMethods
	if len(supportMethods) <= 0 {
		return true
	}

	for _, method := range supportMethods {
		if method == r.Method {
			return true
		}
	}
	return false
}

func checkDomain(route *config.Route, r *http.Request) bool {
	if route.Domain == "" || len(route.Domain) <= 0 {
		return true
	}

	return route.Domain == r.Host
}
